# -*- coding: utf-8 -*-
# @Time    : 2020/5/21 10:12
# @Author  : suhong
# @File    : down_routers.py
# @Software: PyCharm
import traceback
import types

import aiohttp

from fastapi import APIRouter, Form
from re_common.baselibrary.tools.all_requests.aiohttp_request import AioHttpRequest
from re_common.baselibrary.tools.all_requests.requests_request import RequestsRequest
from re_common.baselibrary.utils.core.mlamada import bools_string
from re_common.baselibrary.utils.core.requests_core import MsgCode

from app.core.return_info import ReturnInfo, SUCCESS

router = APIRouter()


@router.post("/down/chaoxingqk/detail")
async def down_detail(*, proxy: str = Form(None), url: str = Form(...), mags: str = Form(...)):
    return_info = ReturnInfo()

    HEADER = {
        'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
        'Referer': 'http://qikan.chaoxing.com',
    }
    if mags:
        HEADER['Referer'] = 'http://qikan.chaoxing.com/mag/infos?mags=' + mags
    Proxiesss = None
    if proxy:
        if proxy.startswith("http://"):
            Proxiesss = proxy
        else:
            Proxiesss = "http://" + proxy

    try:
        async with aiohttp.ClientSession() as client:
            async with client.get(r'http://qikan.chaoxing.com' + url, proxy=Proxiesss, headers=HEADER,timeout=30) as r:
                text = await r.text()
                # r = requests.get('http://qikan.chaoxing.com' + url, proxies=Proxiesss, headers=HEADER)
                if r is not None:
                    if r.status == 200:
                        return_info.status = SUCCESS
                        return_info.msg_code = r.status
                        return_info.data = {"html": text}
                    else:
                        return_info.msg_code = r.status
                        return_info.msg = "状态码错误:" + str(r.status)
                        return_info.data = {"url": url, "mags": mags,'text':text, "proxy": proxy}
                else:
                    return_info.msg = "请求错误，没有返回Response"
                    return_info.data = {"url": url, "mags": mags, "proxy": proxy}
                return return_info.todict()
    except Exception as e:
        print(traceback.print_exc())
        return_info.msg = "请求错误，没有返回Response"
        return_info.data = {"url": url, "proxy": proxy, "Exception": str(e)}
        return return_info.todict()


@router.post("/down/chaoxingqk/detail_new")
async def down_detail(*, proxy: str = Form(None), detail_id: str = Form(...), mags: str = Form(...)):
    return_info = ReturnInfo()
    HEADER = {
        'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
        'Referer': 'http://qikan.chaoxing.com',
    }
    if mags:
        HEADER['Referer'] = 'http://qikan.chaoxing.com/mag/infos?mags=' + mags

    url = r'http://qikan.chaoxing.com' + detail_id

    rrq = AioHttpRequest()

    def test_middlerwares(self):
        """
        验证返回码
        :return:
        """
        if self.html.find('您访问的资源不存在') != -1:
            self.resp_dicts["code"] = MsgCode.NO_RESOURCE
            self.resp_dicts["msg"] = "您访问的资源不存在"
            return False, self.resp_dicts
        if self.html.find('请输入验证码') != -1:
            self.resp_dicts["code"] = MsgCode.VER_CODE
            self.resp_dicts["msg"] = "请输入验证码"
            return False, self.resp_dicts
        return True, self.resp_dicts

    rrq.test_middlerwares = types.MethodType(test_middlerwares,rrq)

    rrq.set_url(url).set_header(HEADER).set_proxy(proxy).set_marks([url,'F_mainright fl']).set_middler_list(
        [rrq.status_code_middlerwares,rrq.test_middlerwares, rrq.marks_middlerwares,rrq.end_middlerwares])
    rrq.builder()
    bools, dicts =await rrq.run("get")
    return_info.status = bools_string(bools)
    return_info.msg_code = dicts["code"]
    return_info.msg = dicts["msg"]
    if bools:
        return_info.data = {"html" : rrq.html}
    else:
        return_info.data = {"url": url, "proxy": proxy,"html":rrq.html}
    return return_info.todict()

